<template>
  <div class="createPage">
    <el-form
      ref="form"
      label-width="130px"
      :model="form"
      :rules="ruleForm"
      style="padding-left: 20px"
    >
      <div class="title">所属上级商户</div>
      <el-form-item label="所属上级商户" style="margin-top: 34px" prop="parent">
        <el-cascader
          :disabled="this.$route.query.row? true: false"
          v-model="form.parent"
          ref="cascader"
          :show-all-levels="false"
          class="width604"
          :props="{ checkStrictly: true }"
          :options="parentList"
          @change="handleChange"
        ></el-cascader>
      </el-form-item>
      <div class="title" style="margin-top: 58px; margin-bottom: 34px">
        基本信息
      </div>
      <el-form-item label="子商户名称" prop="memberName">
        <el-input
          v-model="form.memberName"
          class="width604"
          maxlength="50"
          placeholder="请填写商户名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="商户ID" prop="memberNo">
        <el-input
          v-model="form.memberNo"
          class="width604"
          placeholder="商户ID一经设置，不可更改"
        ></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          class="width604"
          maxlength="50"
          placeholder="请填写备注"
        ></el-input>
      </el-form-item>
      <div class="title" style="margin-top: 48px; margin-bottom: 34px">
        邀请登录
      </div>
      <el-form-item label="邀请子商户登录" prop="memberEmail">
        <el-input
        maxlength="30"
          v-model="form.memberEmail"
          class="width604"
          placeholder="请输入子商户登录邮箱地址"
        ></el-input>
      </el-form-item>
      <el-form-item label="允许子商户退款" prop="refundFlag">
        <el-switch v-model="form.refundFlag"> </el-switch>
      </el-form-item>
      <!-- <el-form-item label="">
        <div class="submit" @click="submit('form')">提交</div>
      </el-form-item> -->
      <el-form-item label="" style="margin-top: 60px">
        <el-button
          class="width120"
          @click="
            () => {
              this.$backTo('/merchant/childManagement');
            }
          "
          >取消</el-button
        >
        <el-button class="width120" @click="submit('form')" type="primary"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getUserInfo } from "@/utils/public";
import { isEmail } from "@/utils/validate";
import { mapMutations } from "vuex";
import base64 from '@/utils/code';

export default {
  name: "createChild",
  data() {
    const checkEmail = (rule, value, callback) => {
      if (isEmail(value) || value == "") {
        callback();
      } else {
        callback(new Error("请输入有效的邮箱地址"));
      }
    };
    const checkId = (rule, value, callback) => {
      if (/^[A-Za-z0-9]+$/.test(value)) {
        callback();
      } else {
        callback(new Error("商户ID由字母数字组成"));
      }
    };
    return {
      treeLevel: "",
      parent: [],
      parentList: [],
      form: {
        memberEmail: "",
        remark: "",
        memberNo: "",
        memberName: "",
        refundFlag: false,
        parent: [],
      },
      ruleForm: {
        parent: [
          { required: true, message: "请选择所属上级商户", trigger: "change" },
        ],
        memberName: [
          { required: true, message: "请输入子商户名称", trigger: "change" },
          {
            pattern: /^(?!\s+).*(?<!\s)$/,
            message: "格式有误",
            trigger: "change",
          },
        ],
        memberNo: [
          { required: true, message: "请输入商户ID", trigger: "change" },
          { validator: checkId, trigger: "change" },
          { min: 8, message: "最小长度8字符", trigger: "change" },
          { max: 30, message: "最大长度30字符", trigger: "change" },
        ],
        memberEmail: [
          // {
          //   required: false,
          //   message: "请输入子商户登录邮箱地址",
          //   trigger: "change",
          // },
          { validator: checkEmail, trigger: "change" },
        ],
      },
    };
  },
  created() {
    let qRow = this.$route.query.row?JSON.parse(base64.decode(this.$route.query.row)): null;
    // console.log(JSON.parse(base64.decode(this.$route.query.row)));
    this.$http.get("/api/merchant/memberbase/getTree").then((res) => {
      this.parentList = this.deepArr(res.data);
      this.treeLevel = res.data[0].level - 1;
      if (this.$route.query.row) {
        this.form.parent = qRow.id;
        let arr2 = [];
        const each = (arr, i) => {
          arr.forEach((item) => {
            arr2[i] = item.value;
            if (item.value === this.$route.query.row.id) {
              throw new Error("111");
            } else {
              if (item.children) {
                each(item.children, i + 1);
              }
            }
          });
        };
        try {
          each(this.parentList, 0);
        } catch (e) {
          if (e.message === "End Loop") throw e;
        }
        this.parent = [...arr2];
      } else {
        this.form.parent.push(getUserInfo().memberId);
      }
    });
  },
  watch: {
    "$store.state.testLine": {
      handler(val) {
        if (this.$route.name == this.$options.name) {
          if (val) {
            this.$store.commit("changeTestMode", true);
          }
        }
      },
    },
    deep: true,
  },
  // beforeDestroy() {
  //   this.$store.dispatch('getTree')
  // },
  methods: {
    ...mapMutations(["changeLive"]),
    testCancel() {
      this.$store.commit("changeLive", false);
      setTimeout(() => {
        this.$store.commit("changeLive", true);
      }, 0);
      this.$backTo("/merchant/childManagement");
      // this.$store.commit("changeCheckedMenuItem", {
      //   index: "1-2",
      // });
    },
    getUserInfo,
    deepArr(arr) {
      return arr.map((item) => ({
        label: item.name,
        value: item.id,
        children: item.children.length ? this.deepArr(item.children) : null,
      }));
    },
    handleChange() {
      //console.log(value);
    },
    submit(form) {
      if (this.$refs.cascader.getCheckedNodes()[0].level + this.treeLevel > 6) {
        this.$message.warning("七级商户以下不能创建下级！");
      } else {
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.$http
              .post("/sys/user/register/link", {
                ...this.form,
                appId: this.$store.state.appId,
                parentId:
                  typeof this.form.parent == "object"
                    ? this.form.parent.at(-1)
                    : this.form.parent,
                memberLevel:
                  this.$refs.cascader.getCheckedNodes()[0].level +
                  this.treeLevel +
                  1,
              })
              .then((res) => {
                if (res.code === "0000") {
                  this.$message.success("创建成功！");
                  this.testCancel();
                  // this.$backTo("/merchant/childManagement");
                }
              });
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.createPage {
  background: #fff;
  padding: 34px 0 37px 34px;
  min-width: 1200px;

  .title {
    color: #4f595f;
    position: relative;
    font-size: 20px;
    font-weight: 600;
    margin-left: -20px;
    &::before {
      content: "";
      width: 4px;
      height: 24px;
      background: #03bfc6;
      position: absolute;
      left: -34px;
      top: 3px;
    }
  }
  .width604 {
    width: 604px;
  }
}
</style>
